﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Antlr3.ST;
using System.IO;
using Lyh.Dbdg.Model;

namespace Lyh.Dbdg.UI
{
    public class DocumentBuilder
    {
        public static void Save(string savePath, Database db)
        {
            var currentFolder = Environment.CurrentDirectory;
            var saveFolder = string.Format("{0}\\{1}", savePath, db.Name);
            var indexText = File.ReadAllText(string.Format("{0}\\Template\\Default\\index.htm", currentFolder),Encoding.UTF8);
            var leftText = File.ReadAllText(string.Format("{0}\\Template\\Default\\left.htm", currentFolder), Encoding.UTF8);
            var tableText = File.ReadAllText(string.Format("{0}\\Template\\Default\\table.htm", currentFolder), Encoding.UTF8);
            var stIndex = new StringTemplate(indexText);
            var stLeft = new StringTemplate(leftText);
            var stTable = new StringTemplate(tableText);

            stIndex.SetAttribute("Database", db);
            stLeft.SetAttribute("Database", db);
            stLeft.SetAttribute("Tables", db.Tables);
            stTable.SetAttribute("Tables", db.Tables);

            CopyFolder(currentFolder + "\\Template\\Default", saveFolder);
            WriteFile(saveFolder + "\\index.htm", stIndex.ToString());
            WriteFile(saveFolder + "\\left.htm", stLeft.ToString());
            WriteFile(saveFolder + "\\table.htm", stTable.ToString());
        }

        public static bool WriteFile(string filePath,string context)
        {
            bool flage = false;
            try
            {
                FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite);
                StreamWriter w = new StreamWriter(fs, Encoding.UTF8);
                w.BaseStream.Seek(0, SeekOrigin.End);

                w.Write(context);
                w.Flush();
                w.Close();
                w.Dispose();
                fs.Close();
                fs.Dispose();
            }
            catch
            {
                flage = false;
            }

            return flage;
        }

        public static void CopyFolder(string sourcePath, string destinPath)
        {
            if (!Directory.Exists(destinPath))
            {
                Directory.CreateDirectory(destinPath);
            }

            DirectoryInfo root = new DirectoryInfo(sourcePath);
            FileInfo[] files = root.GetFiles();
            foreach (FileInfo file in files)
            {
                file.CopyTo(destinPath + "\\" + file.Name, true);
            }

            DirectoryInfo[] childs = root.GetDirectories();
            foreach (DirectoryInfo child in childs)
            {
                CopyFolder(child.FullName, destinPath + "\\" + child.Name);
            }
        }
    }
}